// $codepro.audit.disable com.instantiations.assist.eclipse.analysis.audit.rule.effectivejava.constructorsOnlyInvokeFinalMethods, numericLiterals
/*
 * ServerDiscoveryFrame.java
 */
package edu.gatech.oad.networking;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.awt.event.MouseAdapter;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.ListSelectionModel;

public class ServerDiscoveryFrame extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private final JPanel contentPane;
	
	private final JList list;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					final ServerDiscoveryFrame frame = new ServerDiscoveryFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ServerDiscoveryFrame() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		final JLabel lblConnectToMufasa = new JLabel("Connect to M.U.F.A.S.A. Server");
		contentPane.add(lblConnectToMufasa, BorderLayout.NORTH);
		
		list = new JList();
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
		        if (e.getClickCount() == 2) {
		            final int index = list.locationToIndex(e.getPoint());
		            System.out.println("Connect by double-click to " +
		            		list.getModel().getElementAt(index));
		            ClientManager.sharedManager().connectToServer(index);
		         }
		    }
		});
		contentPane.add(list, BorderLayout.CENTER);
		
		final JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.SOUTH);
		panel.setLayout(new BorderLayout(0, 0));
		
		final JButton btnConnect = new JButton("Connect");
		btnConnect.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				System.out.println("Connect to " + list.getSelectedValue());
				ClientManager.sharedManager().connectToServer(list.getSelectedIndex());
			}
			
		});
		panel.add(btnConnect, BorderLayout.EAST);
	}
	
	public void beginDiscovery() {
		try {
			list.setModel(ClientManager.sharedManager());
			ClientManager.sharedManager().setupNetworking();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
